<template>
  <TreeSelect
    v-model="value"
    :options="options"
    :selectionMode="selectionMode"
    :display="selectionMode == 'multiple' ? 'chip' : 'comma'"
    :disabled="disabled"
    :placeholder="placeholder"
    @change="$emit('change', value)"
  />
</template>
<script>
export default {
  name: 'DeptTreeSelect',
  emits: ['update:modelValue', 'change'],
  props: {
    modelValue: {
      required: true,
    },
    placeholder: {
      default: () => {
        return '请选择所属部门'
      },
    },
    disabled: {
      type: Boolean,
      default: () => {
        return false
      },
    },
    selectionMode: {
      type: String,
      default: () => {
        return 'single'
      },
    },
  },
  data() {
    return {}
  },
  computed: {
    options() {
      const dept2Option = (depts, options) => {
        for (let i = 0; i < depts.length; i++) {
          let dept = depts[i]
          let option = {
            key: dept.id,
            label: dept.deptName,
            data: dept.id,
          }

          if (dept.children && dept.children.length > 0) {
            option.children = []

            dept2Option(dept.children, option.children)
          }

          options.push(option)
        }
      }

      const depts = this.$store.getters.depts
      const options = []
      dept2Option(depts, options)
      return options
    },
    personalInfo() {
      return this.$store.getters.personalInfo
    },
    value: {
      get() {
        if (
          this.modelValue === null ||
          this.modelValue === undefined ||
          this.modelValue === ''
        ) {
          return null
        }

        const value = {}
        if (this.selectionMode == 'single') {
          value[this.modelValue] = true
          return value
        }

        this.modelValue.forEach((i) => {
          value[i] = true
        })
        return value
      },
      set(value) {
        const values = Object.keys(value)
        if (this.selectionMode == 'single') {
          if (values.length > 0) {
            this.$emit('update:modelValue', values[0])
          } else {
            this.$emit('update:modelValue', null)
          }
        } else {
          this.$emit('update:modelValue', values)
        }
      },
    },
  },
}
</script>
